<?php

/**
 * 基本模型
 * 表单模型不会映射数据表，而数据模型会映射到表
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/1/18
 * Time: 10:27
 */

namespace common\models\base;

use yii\db\ActiveRecord;


class BaseModel extends ActiveRecord
{

    /**
     * 获取公共数据
     * @param $query
     * @param int $curPage
     * @param int $pageSize
     * @param null $search
     * @return array
     */
    public function getPages($query, $curPage = 1, $pageSize = 10, $search = null)
    {
       // var_dump($query);exit;
        if($search)
            $query = $query->andFileWhere($search);

        $data['count'] = $query->count();
        if(!$data['count']) {
            return ['count'=>0, 'curPage'=>$curPage, 'pageSize'=>$pageSize, 'start'=>0, 'end'=>0, 'data'=>[]];
        }

        //超过实际页数，不去curPage为当前页
        $curPage = (ceil($data['count']/$pageSize)<$curPage)?ceil($data['count']/$pageSize):$curPage;

        //当前页
        $data['curPage'] = $curPage;

        //每页显示条数
        $data['pageSize'] = $pageSize;

        //起始页
        $data['start'] = ($curPage-1)*$pageSize+1;

        //末页
        $data['end'] = (ceil($data['count']/$pageSize) == $curPage)?$data['count']:($curPage-1)*$pageSize+$pageSize;

        //数据
        $data['data'] = $query
            ->offset(($curPage-1)*$pageSize)
            ->limit($pageSize)
            ->asArray()
            ->all();
        return $data;
    }

}